
#include "Buzzer.h"
#include "BSP_Delay.h"
#include "BSP_Buzzer.h"
#include "Timer.h"

static Timer_T buzzerTimer;

static uint8_t buzzerLock;
static uint16_t buzzerBeepCount;
static uint32_t buzzerOnTime;
static uint32_t buzzerOffTime;

static uint32_t buzzerCount;

static void BuzzerCallback(){
	if(buzzerCount){
		--buzzerCount;
		if(buzzerCount){
			return;
		}
	}
	else{
		return;
	}
	
	if(buzzerBeepCount > 0){
		if(BSP_Buzzer_State()){
			BSP_Buzzer_Set(0);
			buzzerCount = buzzerOffTime;
		}
		else{
			BSP_Buzzer_Set(1);
			buzzerCount = buzzerOnTime;
		}
		
		--buzzerBeepCount;
		if(buzzerBeepCount == 0){
			BSP_Buzzer_Set(0);
			Timer_Stop(&buzzerTimer);
		}
	}
}


void Buzzer_Init(void){
	BSP_Buzzer_Set(0);
	Timer_Setup(&buzzerTimer, 1, 1, 0, BuzzerCallback);	
}

void Buzzer_On(void){
	if(buzzerLock){
		return;
	}
	BSP_Buzzer_Set(1);
}

void Buzzer_Off(void){
	if(buzzerLock){
		return;
	}
	BSP_Buzzer_Set(0);
}

void Buzzer_Lock(uint8_t state){
	buzzerLock = state;
}

void Buzzer_AsyncBeepMult(uint8_t count, uint32_t onMs, uint32_t offMs){
	if(buzzerLock){
		return;
	}
	if(count == 0){
		return;
	}
	
	buzzerOnTime = onMs / 10 + 1;
	buzzerOffTime = offMs / 10 + 1;
	buzzerBeepCount = count * 2 - 1;
	buzzerCount = buzzerOnTime;
	BSP_Buzzer_Set(1);
	//设置定时器周期并启动定时器
	Timer_Restart(&buzzerTimer);
}


void Buzzer_Beep(uint32_t ms){
	Buzzer_On();
	BSP_Delay_ms(ms);
	Buzzer_Off();
}

void Buzzer_BeepDuration(uint8_t count, uint32_t ms){
	uint8_t i;
	for(i = 0; i < count; i++){
		Buzzer_On();
		BSP_Delay_ms(ms);
		Buzzer_Off();		
		BSP_Delay_ms(ms);
	}
}

int Buzzer_State(void){
	return BSP_Buzzer_State();
}


